﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using CommunitySystem.Ctrls;
using CommunitySystem.Views;
using System.Xml.Linq;
using CommunitySystem.Common;
using System.Reflection;
using System.Collections.ObjectModel;
using org.in2bits.MyXls;


namespace CommunitySystem.PageView.AdvancedCustomerQuery
{
    public partial class DetailQueryResultControl : AsyncCtrl, IReturnListenerc
    {
        private CustomerQuery.CustomerQueryClient client = null;
        private CustomerQuery.Query_ShowColumn[] _columns = null;
        public DetailQueryResultControl(XElement element, CustomerQuery.Query_ShowColumn[] columns)
        {
            InitializeComponent();
            _columns = columns;
            client = new CustomerQuery.CustomerQueryClient();
            client.QueryDetailInfoCompleted += new EventHandler<CustomerQuery.QueryDetailInfoCompletedEventArgs>(client_QueryDetailInfoCompleted);
            client.QueryDetailInfoAsync(element, new System.Collections.ObjectModel.ObservableCollection<CustomerQuery.Query_ShowColumn>(columns));
            QueryViewClass qvc = new QueryViewClass();
            PropertyInfo[] pi = qvc.GetType().GetProperties();
            for (int i=0; i< columns.Length; i++)
            {
                PropertyInfo p = pi[i];
                DataGridTextColumn col = new DataGridTextColumn() { Binding = new System.Windows.Data.Binding() { Path = new PropertyPath(p.Name) }, Header = columns[i].ColumnName, IsReadOnly = true };
                dataGrid1.Columns.Add(col);
            }
            DataGridTextColumn colindex = new DataGridTextColumn() { Binding = new System.Windows.Data.Binding() { Path = new PropertyPath("index") }, IsReadOnly = true };
            dataGrid1.Columns.Insert(0, colindex);
        }
        ObservableCollection<QueryViewClass> list = null;
        void client_QueryDetailInfoCompleted(object sender, CustomerQuery.QueryDetailInfoCompletedEventArgs e)
        {
            try
            {
                XDocument doc = XDocument.Parse(e.Result);
                XElement root = doc.Root;
                PropertyInfo[] pis =  Type.GetType("CommunitySystem.Common.QueryViewClass").GetProperties();
                list = new ObservableCollection<QueryViewClass>();
                int index = 1;
                foreach (XElement ele in root.Elements())
                {
                    QueryViewClass entity = new QueryViewClass() { index = index++, IsSelected = false };
                    for (int i = 0; i < _columns.Length; i++)
                    {
                        string value = ele.Attribute(_columns[i].ColumnName).Value;
                        if (!string.IsNullOrEmpty(value))
                        {
                            PropertyInfo p = pis[i];
                            p.SetValue(entity, value, null);
                        }
                    }
                    list.Add(entity);
                }
                dataGrid1.ItemsSource = list;
            }
            catch (Exception ex)
            {
            }
        }

        public void BeginReturn()
        {
            return;
        }

        private void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            CheckBox cb = sender as CheckBox;
            if (cb != null && list != null)
            {
                //ObservableCollection<QueryViewClass> list = dataGrid1.ItemsSource as ObservableCollection<QueryViewClass>;
                foreach (QueryViewClass l in list)
                {
                    l.IsSelected = (bool)cb.IsChecked;
                    if (dataGrid1.Columns[1].GetCellContent(l) != null)
                    {
                        CheckBox cb2 = dataGrid1.Columns[1].GetCellContent(l).FindName("cbItem") as CheckBox;
                        cb2.IsChecked = cb.IsChecked;
                    }
                }
                
                    
            }
        }

        private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
        {
            if (list != null)
            {
                if (list.Where(c => c.IsSelected == true).Count() > 0)
                {
                    SilverlightMessageBoxLibrary.Message.InfoMessage("请至少选择一条数据!");
                        return;
                }
                var saveFile = new SaveFileDialog() { Filter = "Excel 1997-2003| *.xls" };
                if (saveFile.ShowDialog() == false)
                    return;
                org.in2bits.MyXls.XlsDocument xls = new org.in2bits.MyXls.XlsDocument();
                var sheet = xls.Workbook.Worksheets.Add("Sheet 1");

              
                org.in2bits.MyXls.XF xf = xls.NewXF();
                xf.HorizontalAlignment = HorizontalAlignments.Centered;
                xf.VerticalAlignment = VerticalAlignments.Centered;
                int rowindex = 1;
                sheet.Rows.AddRow((ushort)rowindex);
                foreach (var column in dataGrid1.Columns)
                {
                    DataGridTextColumn c = column as DataGridTextColumn;
                    if (c != null)
                    {
                        if (c.Binding.Path.Path == "index")
                                continue;
                        object value = c.Header;
                        sheet.Cells.Add(rowindex, c.DisplayIndex - 1, value, xf);
                    }
                }
                rowindex++;
                foreach (var row in list.Where(c=>c.IsSelected == true))
                {
                    sheet.Rows.AddRow((ushort)rowindex);
                    foreach (var column in dataGrid1.Columns)
                    {
                        DataGridTextColumn c = column as DataGridTextColumn;
                        if (c != null)
                        {
                            if (c.Binding.Path.Path == "index")
                                continue;
                            string p = c.Binding.Path.Path;
                            var pi = row.GetType().GetProperty(p);
                            object value = pi.GetValue(row, null);
                            sheet.Cells.Add(rowindex, c.DisplayIndex - 1, value, xf);
                        }
                    }
                    rowindex++;
                }
                
                try
                {
                    System.IO.Stream stream = saveFile.OpenFile();
                    xls.Save(stream);
                    stream.Dispose();
                    SilverlightMessageBoxLibrary.Message.InfoMessage("导出成功!");
                }
                catch (Exception ex)
                {
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("导出失败:\n" + ex.Message);
                }
            }
        }
    }
}
